home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 831 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  48 lines

  1. Path: pwolf-mac.qualcomm.com!user
  2. From: pwolf@qualcomm.com (Paul I. Wolf )
  3. Newsgroups: comp.lang.c
  4. Subject: Re: To malloc (new) or not to malloc?  When is the question.
  5. Date: 9 Jan 1996 17:12:52 GMT
  6. Organization: Qualcomm, Inc.
  7. Message-ID: <pwolf-0901960912510001@pwolf-mac.qualcomm.com>
  8. References: <4ctvk3$ort@maverick.tad.eds.com>
  9. NNTP-Posting-Host: pwolf-mac.qualcomm.com
  10.  
  11. In article <4ctvk3$ort@maverick.tad.eds.com>, fignet05.darrins@eds.com
  12. (Darrin Smith) wrote:
  13. [snip]
  14. > Why is it that you can do something like the following: 
  15. >         char *x; 
  16. >         x="Some really long string with no particular meaning";
  17. > and have no problems, but can't (safely) do something like this:
  18. >         struct st1{char one[10];
  19. >                    char two[20];
  20. >                    char three[10];
  21. >                   }; 
  22. >         st1 *sptr;      //or struct st1 *sptr in C instead of C++ 
  23. >         sptr=fread(....);
  24. > This caused a program I was trying to debug to crash.  When I allocated 
  25. > memory for sptr (I used sptr=new st1; but I suppose malloc would have done 
  26. > just as well) it worked fine.                   
  27. >  
  28. > What is going on here?  Why isn't memory set aside for st1 *sptr just as 
  29. > it is for char *x?  Before I did the new (or malloc) it seemed as though 
  30. > my program was getting written over!
  31. First example is incorrect. You may be thinking of declaring with initializing:
  32.    char* x = "Some really long string with no particular meaning";
  33.  
  34. Same thing works for second example if you initialize with constants:
  35.    struct st1{char one[10];
  36.               char two[20];
  37.               char three[10];
  38.               }* sptr= {0};
  39.  
  40. The point is that memory allocatiion during initialization is required if
  41. you want the pointer to "automatically" point to memory which can be used.
  42. In your first example, the "x=" is NOT valid syntax for a sequence of
  43. characters. In your second example, memory for the structure was not
  44. allocated by your declaration of the pointer, so using the pointer for
  45. "fread()" puts information into unallocated memory.
  46.